﻿using System.Linq;
using System.Web.Mvc;
using SacNetUG.Models;

namespace SacNetUG.Controllers
{
    public partial class SponsorController : Controller
    {
        public virtual ActionResult Index()
        {
            ViewData["RenderAdminLink"] = Models.User.UserInRole(HttpContext.User.Identity.Name, "Admin");
            return View(repository.Db.Table<Sponsor>().OrderBy(e => e.SponsorCategory.SortOrder).OrderBy(e => e.SortOrder));
        }

        [Authorize]
        public virtual ActionResult Create()
        {
            return View();
        }

        [HttpPost, Authorize]
        public virtual ActionResult Create(Sponsor sponsor)
        {
            try
            {
                if (!ModelState.IsValid)
                    return View(sponsor);

                repository.Db.InsertOnSubmit(sponsor);
                repository.Db.SubmitChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        [Authorize]
        public virtual ActionResult Edit(int id)
        {
            if (id == 0) return View(Views.Create);

            return View(repository.Db.Table<Sponsor>().FirstOrDefault(p => p.SponsorId == id));
        }

        [HttpPost, Authorize]
        public virtual ActionResult Edit(int id, Sponsor sponsor)
        {
            try
            {
                if (!ModelState.IsValid)
                    return View(sponsor);

                UpdateModel(repository.Db.Table<Sponsor>().FirstOrDefault(p => p.SponsorId == id));
                repository.Db.SubmitChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public virtual JsonResult GetBannerList()
        {
            var db = new SacNetUGRepository();
            var bannerList = db.Db.Table<Sponsor>().Where(s => s.SponsorCategoryId == 1).Select(s => new { s.Name, s.Url, s.BannerUrl });
            return Json(bannerList.ToArray(),"application/json", JsonRequestBehavior.AllowGet);
        }

        //public virtual JsonResult JsonTest()
        //{
        //    string temp = "HI";
        //    return Json(temp, "application/json", JsonRequestBehavior.AllowGet);
        //}
    }
}